#!/bin/sh

find_x11_headers() {
	if [ -f /usr/include/X11/Xlib.h ]; then
		x11_dir=/usr/include/X11
	elif [ -f /usr/X11R6/include/X11/Xlib.h ]; then
		x11_dir=/usr/X11R6/include/X11
	elif [ -f /usr/X11/include/X11/Xlib.h ]; then
		x11_dir=/usr/X11/include/X11
	else
		echo failed to locate X11 header files, make sure they are installed!
	fi
}

prefix=/usr/local
opt=yes
dbg=yes

echo 'configuring gxbase ...'

# locate the Xlib header path
find_x11_headers

# parse command line options
for arg; do
	case "$arg" in
	--prefix=*)
		value=`echo $arg | sed 's/--prefix=//'`
		prefix=${value:-$prefix}
		;;
	
	--enable-opt)
		opt=yes;;
	--disable-opt)
		opt=no;;

	--enable-debug)
		dbg=yes;;
	--disable-debug)
		dbg=no;;

	--help)
		echo 'usage: ./configure [options]'
		echo 'options:'
		echo '  --prefix=<path>: installation path (default: /usr/local)'
		echo '  --enable-opt: enable speed optimizations (default)'
		echo '  --disable-opt: disable speed optimizations'
		echo '  --enable-debug: include debugging symbols (default)'
		echo '  --disable-debug: do not include debugging symbols'
		echo 'all invalid options are silently ignored'
		exit 0
		;;
	esac
done

# check for xrandr header presence
if [ -f $x11_dir/extensions/Xrandr.h ]; then
	echo 'found XR&R extension header, will attempt to use it.'
	extra_defs='-DUSE_XRANDR '
else
	echo 'XR&R extension header not found.'
fi

# check for xf86vm header presence
if [ -f $x11_dir/extensions/xf86vmode.h ]; then
	echo 'found XF86VidMode extension header, will attempt to use it.'
	extra_defs="$extra_defs-DUSE_XF86VM "
else
	echo 'XF86VidMode extension header not found.'
fi

echo "prefix: $prefix"
echo "optimize for speed: $opt"
echo "include debugging symbols: $dbg"

# generate the makefile
echo 'creating makefile ...'
echo '# this Makefile is automatically generated, do not modify' >Makefile
echo "PREFIX = $prefix" >>Makefile

if [ "$dbg" = yes ]; then
	echo 'dbg = -g' >>Makefile
fi
if [ "$opt" = yes ]; then
	echo 'opt = -O3' >>Makefile
fi
if [ "`uname -s`" = Darwin ]; then
	echo 'shared = -dynamiclib' >>Makefile
	echo 'so = dylib' >>Makefile
else
	echo 'shared = -shared' >>Makefile
	echo 'so = so' >>Makefile
	echo 'pic = -fPIC' >>Makefile
fi

cat Makefile.in >>Makefile

echo 'configuration completed, type make (or gmake) to build.'
